﻿namespace Sidvall.Data.Sqlite
{
    public abstract class StorageManagerBase : System.IDisposable
    {
        #region Public Members

        protected global::SQLite.Net.SQLiteConnection Connection { get; set; }

        public void Dispose()
        {
            Dispose(true);
            System.GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    if (Sidvall.Data.Sqlite.SystemContext.Current.CurrentTransaction == null)
                    {
                        if (this.Connection != null)
                            this.Connection.Close();
                    }
                    this.Connection = null;
                }
                disposed = true;
            }
        }

        #endregion
        #region Private Members

        private bool disposed = false;

        #endregion
        #region Constructors

        protected StorageManagerBase(string databasePath)
        {
            this.Connection = new SQLite.Net.SQLiteConnection(global::Sidvall.Data.Sqlite.SystemContext.Current.SQLitePlatform, databasePath, storeDateTimeAsTicks: false);
            this.Connection.ExecuteScalar<string>("PRAGMA foreign_keys = ON", new object[] { });
            if (Sidvall.Data.Sqlite.SystemContext.Current.CurrentTransaction != null)
                Sidvall.Data.Sqlite.SystemContext.Current.CurrentTransaction.Connection = this.Connection;
        }

        #endregion
    }
}
